﻿create PROCEDURE Sync.SP_BoardAttendees_ApplyChanges
@RawValues XML 
AS 
BEGIN
	 
		DECLARE @BoardAttendees_Temp TABLE 
		(
			BoardAttendeesID UniqueIdentifier,
			[BoardID] uniqueidentifier,
				[UserID] uniqueidentifier,
			IsDeleted BIT, 
			LastUpdatedDate DATETIME
		)
		
	   INSERT INTO @BoardAttendees_Temp 
	   SELECT	Tbl.Col.value('BoardAttendeesID[1]','uniqueidentifier') BoardAttendeesID,
                Tbl.Col.value('BoardID[1]', 'uniqueidentifier') [BoardID],
Tbl.Col.value('UserID[1]', 'uniqueidentifier') [UserID],
				Tbl.Col.value('IsDeleted[1]', 'bit') IsDeleted,
				Tbl.Col.value('LastUpdatedDate[1]','DateTime') LastUpdatedDate
	   FROM   @RawValues.nodes('/DocumentElement/BoardAttendees') Tbl(Col)
----------------------------------------------------------------------------------------

-- Insert ------------------------------------------------------------------------------

	INSERT INTO [dbo].[BoardAttendees] ([BoardAttendeesID],[BoardID],[UserID])
	SELECT t.[BoardAttendeesID],t.[BoardID],t.[UserID]
	FROM  @BoardAttendees_Temp t
	WHERE t.IsDeleted = 0
    AND NOT EXISTS
    (
        SELECT 1 FROM sync.BoardAttendees_Tracking s
        WHERE t.BoardAttendeesID = s.BoardAttendeesID
    )
	-- put conflicts here.
	
-- Update -------------------------------------------------------------------------------
     
	UPDATE [dbo].[BoardAttendees]
	SET [BoardAttendees].[BoardID] = t.[BoardID],[BoardAttendees].[UserID] = t.[UserID] 
	FROM [dbo].[BoardAttendees] s JOIN @BoardAttendees_Temp t 
    ON t.BoardAttendeesID = s.BoardAttendeesID
	WHERE	t.IsDeleted = 0 
	AND		t.LastUpdatedDate IS NOT NULL
	AND		t.LastUpdatedDate >= 
				 isnull((SELECT TOP 1 LastUpdatedDate 
				  FROM sync.BoardAttendees_Tracking r
				  WHERE t.BoardAttendeesID = r.BoardAttendeesID)
                  ,t.LastUpdatedDate)
	-----------------------------------------------------------------------------------------

-- Delete -------------------------------------------------------------------------------

	DELETE [dbo].[BoardAttendees]
    FROM @BoardAttendees_Temp t JOIN [dbo].[BoardAttendees] s
    ON t.BoardAttendeesID = s.BoardAttendeesID
	WHERE t.IsDeleted = 1

-----------------------------------------------------------------------------------------
	
END











